# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import Context, loader
from django.http import HttpResponse

from config import *
from contrib.sphinxapi import *
import string
import re

def sanitizeQueryWords(str, encoding = QUERY_STRING_ENCODING):
    #replace Chinese space and full-shaped space with normal English space
    if not str:
        return None
    if not isinstance(str, unicode):
        mystring = str.decode(encoding)
    else:
        mystring = str
    mystring = re.sub(r"[ |　]+", " ", mystring)
    #return mystring
    querywords2 = string.split(mystring, " ")
    querywords = []
    for w in querywords2:
       w = string.strip(w)
       if w:
           querywords.append(w)
    return querywords

def searchit(keywords, sex=0, age=0, marriage=0, province=0, city=0, offset=0, limit=SEARCH_PAGE_SIZE, type='qzone', idx_name="qzone_blog_idx", host=SE_HOST, port=SE_PORT, mode=SPH_MATCH_EXTENDED2, ranker=SPH_RANK_PROXIMITY_BM25, groupby="authorseq", groupsort="@weight,desc"):
    if type == 'msn':
        idx_name = 'msn_blog_idx'
        host = '127.0.0.1'
    cl = SphinxClient()
    cl.SetServer ( host, port )
    cl.SetMatchMode(mode)
    cl.SetWeights ( [100, 1] )
    cl.SetGroupBy ( groupby, SPH_GROUPBY_ATTR, groupsort )
    cl.SetLimits ( offset, limit, (limit if limit>1000 else 1000))
    cl.SetRankingMode ( ranker );
    if sex and (sex == 1 or sex == 2):
        cl.SetFilter('sex', [sex])
    if type == 'qzone':
        cl.SetFilter('onlinestatus', [3], 3200000)
    if sex:
        if age == 1:
            cl.SetFilterRange('age', 0, 15, 1600000)
        elif age == 2:
            cl.SetFilterRange('age', 16, 22, 1600000)
        elif age == 3:
            cl.SetFilterRange('age', 23, 30, 1600000)
        elif age == 4:
            cl.SetFilterRange('age', 31, 40, 1600000)
        elif age == 5:
            cl.SetFilterRange('age', 41, 1000, 1600000)
    if province:
        cl.SetFilter('province', [province], 800000)
    if city:
        cl.SetFilter('city', [city], 400000)
    if marriage:
        cl.SetFilter('marriage', [marriage], 200000)
    res = cl.Query ( keywords, idx_name )
    return res

